#include "login.h"
#include "ui_login.h"
#include<QtNetwork/QUdpSocket>
#include<QtNetwork/QNetworkDatagram>

Login::Login(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Login)
{
    ui->setupUi(this);
    setWindowTitle("登录");

    udp=new QUdpSocket(this);
    connect(udp,&QUdpSocket::readyRead,this,&Login::connecthandle);
}

Login::~Login()
{
    delete ui;
}


void Login::on_pushButton_register_3_clicked()
{
    Register* re=new Register(udp);
    re->show();
}

void Login::connecthandle()
{
   const QNetworkDatagram& responseDatagram = udp->receiveDatagram();
    QString response = responseDatagram.data();
    qDebug()<<response;
    if(response.length()==0)
        return;
    if(response[0]=='M')
    {

    }
    else if(response[0]=='H')
    {
        identity=ui->comboBox_3->currentIndex();
        QString name(response.begin()+2);
        if(identity==0)
        {
        disconnect(udp,&QUdpSocket::readyRead,this,&Login::connecthandle);
        WorkUI* wk=new WorkUI(nullptr,name,ui->lineEdit_5->text(),udp);

        wk->show();
        udp=nullptr;
        this->close();
        }
        else
        {
            disconnect(udp,&QUdpSocket::readyRead,this,&Login::connecthandle);
            Carui* cr=new Carui(nullptr,name,ui->lineEdit_6->text(),udp);
            cr->show();
            udp=nullptr;
            this->close();
        }

    }

}

void Login::on_pushButton_login_3_clicked()
{    
    identity=ui->comboBox_3->currentIndex();
    QString r=identity==0?"merchant":"courier";
    QString a="U,"+ui->lineEdit_5->text()+","+r+","+ui->lineEdit_6->text();
    qDebug()<<a;
    QNetworkDatagram q(a.toUtf8(),QHostAddress("127.0.0.1"),12345);
    udp->writeDatagram(q);
qDebug() << "数据报已发送到" << q.destinationAddress().toString() << ":" << q.destinationPort();
}
